﻿#region Usings
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web.Mvc;
using BK.Model;
using BK.Model.ViewModels;
using BK.Repositories.Abstract;

#endregion Usings

namespace BK.Web.UI.Controllers
{
	public class UsersController : BaseController<User>
	{
		#region C'tors

		public UsersController(IUsersRepository entitiesRepository)
            : base(entitiesRepository, entitiesRepository)
		{
		}

		#endregion C'tors

		#region Instance Methods

		public override ActionResult Delete(int id)
		{
			User user = EntitiesRepository.GetById(id);

			if (user == null)
			{
				return View("NotFound");
			}

			return View(user);
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Delete(int id, string confirmButton)
		{
			User user = EntitiesRepository.GetById(id);

			if (user == null)
				return View("NotFound");

			EntitiesRepository.Delete(user);
			
			return View("Deleted");
		}

		public ActionResult Details(int id)
		{
			User user = EntitiesRepository.GetById(id);
			return user == null ? View("NotFound") : View(user);
		}

		public ActionResult Edit(int id)
		{
			User user = EntitiesRepository.GetById(id);
			return View(user);
		}

		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult Edit(int id, FormCollection formValues)
		{
			User user = EntitiesRepository.GetById(id);
			try
			{
				UpdateModel(user, formValues.ToValueProvider());
				EntitiesRepository.Save();
				return RedirectToAction("Details", new { id = user.Id });
			}
			catch
			{
				return View(user);
			}
		}

		public ActionResult Login(string email, string password)
		{
			return View((User)null);
		}

		public ViewResult Index([DefaultValue(1)] int page)
		{
			UsersListViewModel model = new UsersListViewModel();

			IEnumerable<User> allEntities = EntitiesRepository.GetAll();

			model.PagingInfo.TotalItems = allEntities.Count();

			model.Users = allEntities.Skip((page - 1) * PageSize).Take(PageSize).ToList();

			model.PagingInfo.CurrentPage = page;
			model.PagingInfo.ItemsPerPage = PageSize;

			return View("Index", model);
		}

		#endregion Instance Methods
	}
}